package com.shareach.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;

import com.benayn.ustyle.logger.Loggers;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class HelperUtil {
	
	protected static final Log log = Loggers.from(HelperUtil.class);
	
	/**
	 * 转成base64编码
	 * @param value
	 * @return
	 * @throws IOException
	 */
	public static byte[] fromBase64(String value) throws IOException{
		BASE64Decoder decoder = new BASE64Decoder();
		//Base64解码
		byte[] b = decoder.decodeBuffer(value);
		for(int i=0;i<b.length;++i){
		    if(b[i]<0){//调整异常数据
		        b[i]+=256;
		    }
		}
		return b;
	}
	
	/**
	 * 获取base64编码
	 * @param value
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String toBase64(String value) throws UnsupportedEncodingException{
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(value.getBytes("utf-8"));
	}
	/**
	 * 生成MD5码
	 * @param s
	 * @return
	 */
	public final static String md5(String s) {  
	    char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
	            'a', 'b', 'c', 'd', 'e', 'f' };  
	    try {  
	        byte[] strTemp = s.getBytes();  
	        MessageDigest mdTemp = MessageDigest.getInstance("MD5");  
	        mdTemp.update(strTemp);  
	        byte[] md = mdTemp.digest();  
	        int j = md.length;  
	        char str[] = new char[j * 2];  
	        int k = 0;  
	        for (int i = 0; i < j; i++) {  
	            byte byte0 = md[i];  
	            str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
	            str[k++] = hexDigits[byte0 & 0xf];  
	        }  
	        return new String(str);  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	        return null;  
	    }  
	}  
	/**
	 * 转换成数字
	 * @param value
	 * @return
	 */
	public static long idToNnmber(String value){
		return IdConvert.IdToNnmber(value);
	}
	
	/**
	 * 转换成字符串
	 * @param value
	 * @return
	 */
	public static String idFromNumber(long value){
		return IdConvert.IdFromNnmber(value);
	}
	/**
	 * 转换成字符串
	 * @param value
	 * @param len
	 * @return
	 */
	public static String idFromNumber(long value,int len){
		return IdConvert.IdFromNnmber(value,len);
	}

	/**
	 * 获取不含区号的电话号码，包括手机、固定电话、特服号
	 * @param telPrefix 区号
	 * @param input
	 * @return
	 */
	public static List<String> getTels(String telPrefix , String input){
		Pattern p = Pattern.compile("(\\d{7,})", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(input);
		List<String> result = new ArrayList<String>();
		while(m.find()){
			String tel = m.group(1);
			if(tel.startsWith(telPrefix)){
				tel = tel.substring(telPrefix.length());
			}
			result.add(tel);
		}
		return result;
	}
	public static void main(String[] args){
		List<String> result = getTels("0571","asdf13933334444,0571-87855581 057199994444阿斯顿发就");
		log.debug(result);
	}
	/**
	 * Id转换器类
	 * @author apple
	 *
	 */
	private static class IdConvert{
		public static final String Keys = "Bc3S5qFaCsIioTu8VgY4PAhjL7Xz0QWmbnUxOGtZ6HwDr1JKvdf2EepRyNklM";// 0用作分割符号了，补充了_
		private static final int radix = 61;
		private static final char separatorChar = '9';

		/**
		 * 10进制向62进制转换
		 * 
		 * @param value
		 * @return
		 */
		public static String IdFromNnmber(long value) {
			return IdFromNnmber(value,12);
		}

		/**
		 * 返回62进制数据，并且补充填充字符
		 * 
		 * @param value
		 * @param totalLen
		 * @return
		 */
		public static String IdFromNnmber(long value, int totalLen) {
			if (value == 0) 
				return null;
			String result = "";
			while (value > 0) {
				long val = value % radix;
				result = Keys.charAt((int) val) + result;
				value = value / radix;
			}
			int resultLen = result.length();
		    if (resultLen == (totalLen - 1)) {
				result = separatorChar + result;
			} else {
				result = fillChar(result, totalLen - 1 - resultLen) + separatorChar
						+ result;
			}
			return result;
		}

		private static String fillChar(String str, int len) {
			String uuid = DigestUtils.md5Hex(str).replace(separatorChar, 'a');
			return uuid.substring(uuid.length() - len);
		}
		/**
		 * 62进制数向10进制转换
		 * 
		 * @param value
		 * @return
		 */
		public static long IdToNnmber(String value) {
			int idxSep = value.indexOf(separatorChar);
			if (idxSep > -1) {
				value = value.substring(idxSep + 1);
			}
			int length = value.length();
			long result = 0;
			for (int i = 0; i < length; i++) {
				long val = (long) Math.pow(radix, (length - i - 1));
				char c = value.charAt(i);
				int tmp = Keys.indexOf(c);
				result += (tmp * val);
			}
			return result;
		}
	}
}
